import {Injectable} from "@nestjs/common";
import {InjectModel} from "@nestjs/mongoose";
import {Model} from "mongoose";
import {Score, UserScoreDocument} from "./userScore.schema";
import {UserScore} from "../../../common/interfaces/userScore";

interface Config {
    [key: string]: any
}

@Injectable()
export class UserScoreService {
    constructor(
        @InjectModel("user_score_book") private readonly userScoreModel: Model<UserScoreDocument>
    ) {
    }

    async save(config: UserScore): Promise<Score> {
        const {bookId,userId,score} = config
        const filter = { bookId,userId };
        const update = { score };
        const options = { upsert: true, new: true, runValidators: true };
        return this.userScoreModel.findOneAndUpdate(filter, update, options).exec();
    }

    async find(where: Config) {
        where = this.filter(where)
        return await this.userScoreModel.find(where).exec()
    }


    /* 将传递的条件对象进行处理 */
    private filter(where: Config) {
        Object.keys(where).forEach(item => {
            if (!where[item]) {
                console.warn(`键 ${item} 必须指定具体值`)
                delete where[item]
            }
        })
        return where

    }
}
